package com.coastwe.dahua.chapter03;

public class LinkListDaHua {
    private Node head;
    private int size;

    public LinkListDaHua() {
        head = createNode(0);
        size = 0;
    }

    public int getElem(int index) {
        if (index < 0 || index >= size) {
            System.out.println("查询位置有误");
            return -1;
        }
        Node p = head.next;
        int j = 0;
        while (p != null && j < index) {
            p = p.next;
            ++j;
        }
        return p.data;
    }

    public boolean listInsert(int index, int value) {
        if (index < 0 || index > size) {
            System.out.println("插入位置有误");
            return false;
        }
        Node p = createNode(value);
        Node temp = head;
        for (int i = 0; i < index; i++) {
            temp = temp.next;
        }
        p.next = temp.next;
        temp.next = p;
        size++;
        return true;
    }

    public boolean listDel(int index) {
        if (index >= size) {
            System.out.print("删除位置有误");
            return false;
        }
        Node temp = head;
        for (int i = 0; i < index; i++) {
            temp = temp.next;
        }
        temp.next = temp.next.next;
        size--;
        return true;
    }

    public void printAll() {
        Node temp = head;
        for (int i = 0; i < size; i++) {
            temp = temp.next;
            System.out.print(temp.data + " ");
        }
        System.out.println();
    }

    public void listTraverse() {
        if (head.next == null || head.next.next == null) {
            return;
        }

        Node p = head.next;
        Node temp = p, cacheNode = null;
        for (int i = 0; i < size; i++) {
            temp = p.next;
            p.next = cacheNode;
            cacheNode = p;
            if (temp != null) {
                p = temp;
            }
        }
        head.next = p;
    }

    public static void main(String[] args) {
        LinkListDaHua list = new LinkListDaHua();
        list.listInsert(0, 1);
        list.listInsert(1, 2);
        list.listInsert(2, 3);
        list.listInsert(3, 4);
        list.listInsert(4, 5);
        list.listInsert(5, 6);
        list.printAll();
        list.listInsert(0, 7);
        list.listInsert(3, 7);
        list.listInsert(8, 7);
        list.listInsert(8, 7);
        list.printAll();
        list.listDel(0);
        list.printAll();
        list.listDel(2);
        list.printAll();
        list.listDel(7);
        list.printAll();
        System.out.print("翻转");
        list.listTraverse();
        list.printAll();
    }

    private static Node createNode(int value) {
        return new Node(value, null);
    }

    private static class Node {
        int data;
        Node next;

        Node(int value, Node next) {
            this.data = value;
            this.next = next;
        }
    }
}